package com.wing.purchase.service;


import cn.hutool.core.bean.BeanUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.PurEnum;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.service.DynamicService;
import com.wing.purchase.dao.PurBarterGoodsRecordsDao;
import com.wing.purchase.model.entity.*;

import com.wing.purchase.model.request.PurBarterGoodRecordsUpdateForm;
import com.wing.purchase.model.request.PurReturnGoodRecordsUpdateForm;
import com.wing.purchase.model.request.PurchaseDeliveryRecordForm;
import com.wing.purchase.model.response.PurBarterGoodRecordsSearchVo;
import com.wing.purchase.model.response.PurReturnGoodRecordsSearchVo;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 退货记录-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class PurBarterGoodsRecordsServiceImpl extends ServiceImpl<PurBarterGoodsRecordsDao, PurBarterGoodsRecords> implements PurBarterGoodsRecordsService {
    @Autowired
    private PurBarterGoodsRecordsDetailService purBarterGoodsRecordsDetailService;

    @Autowired
    private DynamicService dynamicService;

    @Autowired
    private PurchaseDeliveryRecordService purchaseDeliveryRecordService;

    @Autowired
    private PurchaseDeliveryRecordProductService purchaseDeliveryRecordProductService;

    /**
     * 查询换货详情
     *
     * @param pg
     * @param params
     * @return
     */
    @Override
    public Page<PurBarterGoodRecordsSearchVo> pageList4app(Page<PurBarterGoodRecordsSearchVo> pg, Map<String, Object> params) {
        List<PurBarterGoodRecordsSearchVo> list = baseMapper.list4app(pg, params);
        pg.setRecords(list);
        return pg;
    }

    /**
     * @param purBarterGoodRecordsUpdateForm
     * @return
     */
    @Override
    @Transactional
    public int addBarterRecordsGoods(PurBarterGoodRecordsUpdateForm purBarterGoodRecordsUpdateForm) {

        //1. 添加记录
        PurBarterGoodsRecords records = new PurBarterGoodsRecords();
        BeanUtil.copyProperties(purBarterGoodRecordsUpdateForm, records, true);
        records.setStatus(PurEnum.barterGoodStatus.DSH.getCode());
        String code = UniqueIdGeneratorUtil.generateUniqueId("HH", "yyyyMMdd", 1000, 9999);
        records.setCode(code);
        records.setCreateTime(LocalDateTime.now());
        records.setCreatorName(JwtUtils.getLoginUsername());
        records.setCreator(JwtUtils.getLoginUserId());
        boolean save = this.save(records);
        if (save) {
            //2. 添加明细
            List<PurBarterGoodsRecordsDetail> purBarterRecordDetails = purBarterGoodRecordsUpdateForm.getPurBarterRecordDetails();
            if (CollectionUtils.isNotEmpty(purBarterRecordDetails)) {
                purBarterRecordDetails.forEach(info -> {
                    info.setRecordId(records.getId());
                    info.setCreateTime(LocalDateTime.now());
                    info.setCreatorName(JwtUtils.getLoginUsername());
                    info.setCreator(JwtUtils.getLoginUserId());
                });
                boolean saveBatch = purBarterGoodsRecordsDetailService.saveBatch(purBarterRecordDetails);
                if (saveBatch) {
                    return 1;
                }
            } else {
                return 1;
            }
        }
        return 0;
    }

    /**
     * 修改换货记录
     *
     * @param form
     * @return
     */
    @Override
    @Transactional
    public int updateBarterRecordsGoods(PurBarterGoodRecordsUpdateForm form) {
        //1.修改记录
        PurBarterGoodsRecords byId = this.getById(form.getId());
        BeanUtil.copyProperties(form, byId, true);
        byId.setStatus(PurEnum.barterGoodStatus.DSH.getCode());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        //如果是修改
        if (form.getButtonType().equals(PurEnum.buttonTypes.UPDATE.getCode())){
            byId.setStatus(PurEnum.barterGoodStatus.DSH.getCode());
        }else if(form.getButtonType().equals(PurEnum.buttonTypes.SEND.getCode())){
            byId.setStatus(PurEnum.barterGoodStatus.DQS.getCode());
        }else {
            byId.setStatus(PurEnum.barterGoodStatus.YQS.getCode());
        }
        boolean b = this.updateById(byId);
        if (!b) {
            return 0;
        }
        QueryWrapper<PurBarterGoodsRecordsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_id", byId.getId());
        boolean remove = purBarterGoodsRecordsDetailService.remove(queryWrapper);
        if (!remove) {
            return 0;
        }
        List<PurBarterGoodsRecordsDetail> purBarterRecordDetails = form.getPurBarterRecordDetails();
        if (CollectionUtils.isNotEmpty(purBarterRecordDetails)) {
            purBarterRecordDetails.forEach(info -> {
                info.setRecordId(byId.getId());
                info.setCreateTime(LocalDateTime.now());
                info.setCreatorName(JwtUtils.getLoginUsername());
                info.setCreator(JwtUtils.getLoginUserId());
            });
        }
        boolean saveBatch = purBarterGoodsRecordsDetailService.saveBatch(purBarterRecordDetails);
        if (!saveBatch) {
            return 0;
        }
        // 2. 如果是确认收货 需要添加一条供应商发货记录
        if (PurEnum.buttonTypes.GET.getCode().equals(form.getButtonType())){
            //拼接供应商发货记录
            PurchaseDeliveryRecord record =new  PurchaseDeliveryRecord();
            record.setCreator(JwtUtils.getLoginUserId());
            record.setCreatorName(JwtUtils.getLoginUsername());
            record.setModifier(JwtUtils.getLoginUserId());
            record.setModifierName(JwtUtils.getLoginUsername());
            record.setLogisticsNo(form.getWaybillNumber());
            record.setPurchaseOrderId(form.getPurOrderId());
            record.setTransportMode(form.getSupplierMethod());
            record.setWaybillNo(form.getSupplierWaybillNo());
            record.setPlateNo(form.getSupplierBusNumber());
            record.setType(PurEnum.deliveryRecordTypes.THH.getCode());
                    //快递单号（待确认）
            record.setCourierNo("");
            record.setPhone(form.getPhone());

            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
            String code = dynamicService.getMaxCode("logistics_no", "pur_purchase_delivery_record");
            String day = simpleDateFormat.format(new Date());
            record.setLogisticsNo("WL"+day+code);
            boolean save = purchaseDeliveryRecordService.save(record);
            if (save) {
                List<PurBarterGoodsRecordsDetail> recordDetails = form.getPurBarterRecordDetails();
                List<PurchaseDeliveryRecordProduct> list = new ArrayList<>();
                recordDetails.forEach(info -> {
                    PurchaseDeliveryRecordProduct product = new PurchaseDeliveryRecordProduct();
                    product.setCreator(JwtUtils.getLoginUserId());
                    product.setModifier(JwtUtils.getLoginUserId());
                    product.setCreatorName(JwtUtils.getLoginUsername());
                    product.setModifierName(JwtUtils.getLoginUsername());
                    product.setCreateTime(LocalDateTime.now());
                    product.setRemark("换货订单"+form.getPurOrderId()+"确认收货自动生成");
                    product.setPurchaseDeliveryRecordId(record.getId());
                    product.setPurchaseOrderDetailId(info.getPurchaseDeliveryRecordDetailId());
                    product.setQuantity(info.getRealGetQuantity());
                    list.add(product);
                });
                purchaseDeliveryRecordProductService.saveBatch(list);
            }
        }
        return 1;
    }


    /**
     * 查询换货详情
     *
     * @param recordId
     * @return
     */
    @Override
    public PurBarterGoodRecordsUpdateForm getByDetailId(String recordId) {
        PurBarterGoodRecordsUpdateForm form = new PurBarterGoodRecordsUpdateForm();
        //1.查询记录信息
        PurBarterGoodsRecords byId = this.getById(recordId);
        BeanUtil.copyProperties(byId, form, true);
        //2. 查询明细信息
        QueryWrapper<PurBarterGoodsRecordsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("record_id", recordId);
        List<PurBarterGoodsRecordsDetail> list = this.purBarterGoodsRecordsDetailService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            form.setPurBarterRecordDetails(list);
        }
        return form;
    }

    /**
     * 删除退货详情
     *
     * @param recordId
     * @return
     */
    @Override
    @Transactional
    public boolean deleteBy(String recordId) {
        boolean b = this.removeById(recordId);
        if (b) {
            QueryWrapper<PurBarterGoodsRecordsDetail> detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("record_id", recordId);
            boolean remove = this.purBarterGoodsRecordsDetailService.remove(detailQueryWrapper);
            if (remove) {
                return true;
            }
        }
        return false;
    }
}
